package com.ksyun.whcg.zhanglulu;

/**
 * @Author: ashtar555
 * @Description: TODO 描述内容
 * @DateTime: 2023/4/21 13:59
 **/
public class PrintThread implements Runnable {
    private static final Object lock = new Object();
    private static String nextThread = "A";
    private String threadId;

    public PrintThread(String threadId) {
        this.threadId = threadId;
    }

    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            synchronized (lock) {
                while (!threadId.equals(nextThread)) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.print(threadId);
                if (threadId.equals("C")) {
                    System.out.println();
                }
                if (nextThread.equals("A")) {
                    nextThread = "B";
                } else if (nextThread.equals("B")) {
                    nextThread = "C";
                } else {
                    nextThread = "A";
                }
                lock.notifyAll();
            }
        }
    }

    public static void main(String[] args) {
        Thread threadA = new Thread(new PrintThread("A"));
        Thread threadB = new Thread(new PrintThread("B"));
        Thread threadC = new Thread(new PrintThread("C"));
        threadA.start();
        threadB.start();
        threadC.start();
    }
}